package com.food.service.impl;

import com.food.common.Result;
import com.food.dto.MealRecordDTO;
import com.food.mapper.MealRecordMapper;
import com.food.model.MealRecord;
import com.food.model.MealRecordDetail;
import com.food.service.MealRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class MealRecordServiceImpl implements MealRecordService {

    @Autowired
    private MealRecordMapper mealRecordMapper;

    @Override
    @Transactional
    public Result<?> addMealRecord(Integer userId, MealRecordDTO mealRecordDTO) {
        MealRecord record = new MealRecord();
        record.setUserId(userId);
        record.setMealType(mealRecordDTO.getMealType());
        record.setRecordDate(mealRecordDTO.getRecordDate());
        record.setRecordTime(mealRecordDTO.getRecordTime());
        
        mealRecordMapper.insert(record);
        
        mealRecordDTO.getItems().forEach(item -> {
            MealRecordDetail detail = new MealRecordDetail();
            detail.setRecordId(record.getRecordId());
            detail.setFoodId(item.getFoodId());
            detail.setQuantity(item.getQuantity());
            mealRecordMapper.insertDetail(detail);
        });
        
        return Result.success(null);
    }

    @Override
    public List<MealRecord> getDailyRecords(Integer userId, LocalDate date) {
        return mealRecordMapper.findByUserIdAndDate(userId, date);
    }

    @Override
    @Transactional
    public Result<?> deleteMealRecord(Integer userId, Integer recordId) {
        try {
            System.out.println("尝试删除记录: recordId=" + recordId + ", userId=" + userId);
            
            MealRecord record = mealRecordMapper.findByIdAndUserId(recordId, userId);
            System.out.println("查询结果: " + (record != null ? "找到记录" : "未找到记录"));
            
            if (record == null) {
                return Result.error("记录不存在或无权限删除");
            }
            
            System.out.println("开始删除主记录");
            mealRecordMapper.deleteById(recordId, userId);
            
            return Result.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败：" + e.getMessage());
        }
    }
} 